package com.feixiang.springbootinit.controller;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.feixiang.springbootinit.common.BaseResponse;
import com.feixiang.springbootinit.common.ResultUtils;
import com.feixiang.springbootinit.constant.WxConstant;
import com.feixiang.springbootinit.model.entity.wechat.MessagePullResponse;
import com.feixiang.springbootinit.model.entity.wechat.NmSubscribers;
import com.feixiang.springbootinit.model.entity.wechat.QwMessage;
import com.feixiang.springbootinit.model.vo.SessionArchive.MessageVO;
import com.feixiang.springbootinit.processor.SessionArchiveBatchProcessor;
import com.feixiang.springbootinit.processor.SessionArchiveProcessor;
import com.feixiang.springbootinit.service.QwMessageService;
import com.feixiang.springbootinit.service.NmSubscribersService;
import com.feixiang.springbootinit.service.SessionArchiveService;
import com.feixiang.springbootinit.wechat.WeComApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/test")
@RestController
@Slf4j
public class TestController {
    @Resource
    private SessionArchiveService sessionArchiveService;

    @Resource
    private QwMessageService messageService;

    @Resource
    private WeComApi weComApi;

    @Resource
    private NmSubscribersService nmSubscribersService;

    @Resource
    private SessionArchiveBatchProcessor sessionArchiveProcessor;

    /**
     * 拉取聊天记录
     * @return
     */
    @GetMapping("/getChatData")
    @ResponseBody()
    public String getChatData() {
        //1.获取数据库的seq当前值，防止重复记录
        Long maxSeq = messageService.getMaxSeq();
        log.info("当前seq值:{}", maxSeq);
        log.info("开始拉取数据...");
        if (maxSeq == null) {
            maxSeq = 0L;
        }
        String chatData = sessionArchiveService.getChatData(maxSeq);
        log.info("拉取加密chatData数据:{}", chatData);
        if (chatData != null) {
            List<QwMessage> messages = sessionArchiveService.decodeChatData(chatData);
            log.info("拉取解密chatData数据:{}", messages);
            return "success";
        } else {
            return "error";
        }
    }
//        拉取加密数据
//        String chatData = sessionArchiveService.getChatData(maxSeq);
//        if (chatData != null) {
//            // 解析为ChatData列表
//            MessagePullResponse response = JSONUtil.toBean(chatData, MessagePullResponse.class);
//            if (response != null && CollectionUtils.isNotEmpty(response.getChatdata())) {
//                // 使用多线程处理消息（替换原有的decodeChatData方法）
//                List<QwMessage> messages = sessionArchiveProcessor.processMessages(response.getChatdata());
//                log.info("拉取解密chatData数据，成功处理消息数量：{}", messages.size());
//                return "success";
//            } else {
//                log.info("拉取到的消息列表为空");
//                return "success";
//            }
//        } else {
//            log.error("获取会话存档数据失败");
//            return "error";
//        }

    /**
     * 查询企微的聊天记录(根据接收方和发送方)
     */
    @PostMapping("/getChatHist")
    public BaseResponse<List<MessageVO>> getChatHist() {
        List<MessageVO> messages = sessionArchiveService.selectChatData("FeiXiang", "wmSDKwCwAAAZ7N9NlW3vT8dazCjScjRA");
        return ResultUtils.success(messages);
    }
    /**
     * 获取企微的认证token
     */
    @GetMapping("/getToken")
    public String getToken() {
        return weComApi.getToken(WxConstant.CORP_ID, WxConstant.CORP_SECRET);
    }

    /**
     * 撤回应用消息
     */
    @Deprecated
    @GetMapping("/recallMessage")
    public String recallMessage(@RequestParam String msgId) {
        return weComApi.recallMessage(msgId);
    }

    /**
     * 获取客户列表
     */
    @GetMapping("/getCustomerList")
    public List<String> getCustomerList() {
        return weComApi.getCustomerList();
    }
    /**
     * 批量获取客户详情
     */
    @GetMapping("/getCustomerDetail")
    public String getCustomerDetail() {
        return weComApi.getCustomerDetail("",50);
    }

    /**
     * 查询所有订户
     */
    @GetMapping("/getAllSubscribers")
    public List<String> getAllSubscribers() {
        return nmSubscribersService.list().stream().map(NmSubscribers::getSubscriberid).collect(Collectors.toList());
    }

}